import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GenTableEntity } from '@entity/tool/genTable.entity';
import {
  ListGenTableDTO,
  CreateGenTableDTO,
  UpdateGenTableDTO,
} from '@dto/tool/genTable.dto';
import { resBuild } from '@utils/resBuild';
import { checkKeyIsExist } from '@utils/serviceHelp';
import { getOperator } from '@utils';

@Provide()
export class GenTableService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(GenTableEntity)
  genTableEntity: Repository<GenTableEntity>;

  // 列表
  async list(queryParams: ListGenTableDTO) {
    const queryBuilder = this.genTableEntity.createQueryBuilder('entity');
    if (queryParams.tableName) {
      queryBuilder.andWhere(
        `entity.tableName like "%${queryParams.tableName}%"`
      );
    }

    // 时间范围，包含全天
    if (queryParams['params[beginTime]'] && queryParams['params[endTime]']) {
      queryBuilder.andWhere(
        'entity.createTime BETWEEN :beginTime AND :endTime',
        {
          beginTime: queryParams['params[beginTime]'] + ' 00:00:00',
          endTime: queryParams['params[endTime]'] + ' 23:59:59',
        }
      );
    }

    if (queryParams.pageNum && queryParams.pageSize) {
      queryBuilder
        .skip((queryParams.pageNum - 1) * queryParams.pageSize)
        .take(queryParams.pageSize);
    }

    const [rows, total] = await queryBuilder.getManyAndCount();
    return resBuild.list(rows, total);
  }

  // 添加
  async create(genTable: CreateGenTableDTO) {
    // 新增之前先判断是否已存在
    await checkKeyIsExist(
      this.genTableEntity,
      'genTableName',
      genTable.tableName
    );
    const myEntity = this.genTableEntity.create(genTable);
    myEntity.setCreateBy(getOperator(this.ctx));
    await this.genTableEntity.save(myEntity);
    return resBuild.success();
  }

  // 删除
  async delete(tableId: string) {
    const ids = tableId.split(',').map(id => Number(id));
    await this.genTableEntity.delete(ids);
    return resBuild.success();
  }

  // 修改
  async update(genTable: UpdateGenTableDTO) {
    const myEntity = this.genTableEntity.create(genTable);
    myEntity.setUpdateBy(getOperator(this.ctx));
    await this.genTableEntity.save(genTable);
    return resBuild.success();
  }

  // 详情
  async detail(tableId: number) {
    const detailInfo = await this.genTableEntity.findOneBy({
      tableId,
    });
    return resBuild.data(detailInfo);
  }
}
